<template>
  <div class="container">
    <el-page-header @back="goBack" content="卖货单"></el-page-header>

    <div class="e-m-t-45 flex" style="justify-content: space-between">
      <div class="e-flex-1">
        <el-button type="primary" icon="el-icon-plus" plain @click="showSellOrder = true">新建卖货单</el-button>
      </div>
      <div class="flex">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="关键字">
            <el-input placeholder="请输入手机号,姓名,订单号,车牌,打包站,站点和站点手机" v-model="key" prefix-icon="el-icon-search"></el-input>
          </el-form-item>
          <!-- <el-form-item label="打包站筛选">
              <el-select v-model="packStationId" clearable placeholder="请选择" @change="getList">
            <el-option v-for="item in stlist" :key="item.id" :label="item.name" :value="item.id"> </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="下单时间">
            <el-date-picker @change="time" :clearable="false" value-format="yyyy-MM-dd" v-model="value1" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" clearable>
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getList">查询</el-button>
            <!-- <el-button @click="downloadwithdrawa()" style="margin-bottom:30px; margin-top: 1px;" type="primary" plain><i
            class="iconfont icon-excel"></i>导出Excel</el-button> -->
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="type-state e-m-b-30">
			<span v-for="(item,index) in statusArr" :key="index" :class="{'on':state == item.value}"
				@click="state=item.value">{{item.name}}</span>
		</div>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column fixed type="index" label="序号" width="50">
      </el-table-column>
      <el-table-column fixed prop="number" label="订单ID" width="200">
      </el-table-column>
      <el-table-column prop="product" label="卖货品类" width="100">
        <template slot-scope="scope">
          <span>{{scope.row.product?scope.row.product.name:'--'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="打包站-后端厂商">
        <template slot-scope="scope">
          <span>{{scope.row.packstation.name}}-{{scope.row.manufacturer.name}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="grossweight" label="毛重（KG）" width="100">
      </el-table-column>
      <!-- <el-table-column prop="tareweight" label="皮重（KG）" width="100">
      </el-table-column>
      <el-table-column prop="netweight" label="净重（KG）" width="100">
      </el-table-column> -->
      <el-table-column prop="weight" label="销售重量（KG）" width="130">
      </el-table-column>
      <el-table-column prop="quantity" label="数量（件）" width="100">
      </el-table-column>
      <el-table-column prop="sellprice" label="单价（元/KG(件)）" width="140">
      </el-table-column>
      <el-table-column prop="sellamount" label="总额（元）" width="100">
      </el-table-column>
      <el-table-column prop="createddatetime" label="建单时间" width="180">
      </el-table-column>
      <!-- <el-table-column prop="endtime" label="卖货时间" width="180">
      </el-table-column> -->
      <el-table-column prop="state" label="订单状态" width="180">
        <template slot-scope="scope">
          <span class="color-success" v-if="scope.row.state == '已完结'">{{scope.row.state}}</span>
          <span class="color-danger" v-else-if="scope.row.state == '已撤销'">{{scope.row.state}}</span>
          <span class="color-warning" v-else>{{scope.row.state}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="100">
        <template slot-scope="scope">
						<nuxt-link class="e-font-12 color-main el-button el-button--text el-button--small" :to="goView(scope.row.id)">查看</nuxt-link>
        </template>
      </el-table-column>
    </el-table>
    <div class="table-pagination" v-if="tableData.length > 0">
      <el-pagination background layout="sizes, total, prev, pager, next" :total="total" :page-sizes="[10, 50, 100, 200]"
        :page-size="pageSize" :current-page="pageIndex" @current-change="pageChange" @size-change="handleSizeChange">
      </el-pagination>
    </div>

    <!-- 新建卖货单 -->
    <el-dialog title="新建卖货单" :visible.sync="showSellOrder" width="800px">
      <el-form :model="form" :rules="rules" ref="form" label-width="auto">
        <div class="flex">
          <div class="e-flex-1">
            <el-form-item label="厂商" prop="manufacturerId">
              <el-select
                v-model="form.manufacturerId"
                placeholder="请选择站点"
              >
                <el-option v-for="item in manufacturerList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="e-flex-1 e-p-l-30">
            <el-form-item label="运送小哥" prop="brotherid">
              <el-select
                v-model="form.brotherId"
                placeholder="请选择运送小哥"
                filterable
              >
                <el-option
                  v-for="item in brotherList"
                  :key="item.id"
                  :label="`${item.name}`"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="flex">
          <div class="e-flex-1">
            <el-form-item label="选择品类">
              <el-cascader ref="chooseType" placeholder="请选择调整后的品类" separator="-" @change="SelectType" filterable :props="{
                  lazy: true,
                  lazyLoad: loadType,
                  label: 'name',
                  value: 'id',
              }" style="width: 100%;margin-right: 20px" v-model="chooseType"></el-cascader>
            </el-form-item>
          </div>
          <!-- <div class="e-flex-1 e-p-l-30">
            <el-form-item label="数量">
              <el-input v-model="form.quantity" type="number" placeholder="请输入"></el-input>
            </el-form-item>
          </div> -->
        </div>
        <div class="flex">
          <div class="e-flex-1">
            <el-form-item label="毛重">
              <el-input v-model="form.grossWeight" type="number" placeholder="请输入毛重（出库重量，用作减库存）"></el-input>
            </el-form-item>
          </div>
          <div class="e-flex-1 e-p-l-30">
            <el-form-item label="销售重量或数量">
              <el-input v-model="form.weight" type="number" placeholder="请输入"></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="flex">
          <div class="e-flex-1">
            <el-form-item label="单价">
              <el-input v-model="form.price" type="number" placeholder="请输入单价"></el-input>
            </el-form-item>
          </div>
          <div class="e-flex-1">
            <el-form-item label="销售金额">
              <el-input v-model="form.sellAmount" type="number" placeholder="请输入销售金额"></el-input>
            </el-form-item>
          </div>
        </div>
        <!-- <div class="flex">
          <div class="e-flex-1">
            <el-form-item label="净重">
              <el-input v-model="form.netWeight" type="number" placeholder="请输入"></el-input>
            </el-form-item>
          </div>
        </div> -->
        <div class="flex">
          <div class="e-flex-1">
            <el-form-item label="备注">
              <!-- <el-input v-model="form.netWeight" type="number" placeholder="请输入"></el-input> -->
              <el-input
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 4}"
                placeholder="请输入内容"
                v-model="form.remarks">
              </el-input>
            </el-form-item>
          </div>
        </div>
        <div class="flex">
          <div class="e-flex-1">
            <el-form-item label="销售证明">
              <div class="pics-list" v-for="(item,index) in form.proves" :key="index">
                <i class="el-icon-error" @click="delPics(index)"></i>
                <el-image
                  :src="fileURL + item"
                  class="item"
                  :preview-src-list="[fileURL + item]"
                >
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>

              <cropper-upload :zoomScale='[1, 1]' :isCropper="false" @getUpload="handleFilesSuccess" class="avatar-uploader">
                  <div class="avatar-uploader-icon">
                      <div><i class="el-icon-plus"></i></div>
                      <div class="e-font-14">上传照片</div>
                  </div>
              </cropper-upload>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showSellOrder = false">取消</el-button>
        <el-button type="primary" @click="createSellOrder">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    layout: 'admin',
    head() {
      return {
        title: '卖货单' 
      }
    },
    data() {
      return {
        timeType:0,//时间类型
        packStationId:null,
        // stlist:'',//打包下拉
        value1:"",//下单时间
        starteate: "",//下单初始
        endDate:"",//下单结束
        loading: true,
        statusArr: [
          {
            name: '全部',
            value: null
          },
          // {
          //   name: '已出库',
          //   value: 0
          // },
          {
            name: '已完结',
            value: 1
          },
          {
            name: '已撤销',
            value: 2
          }
        ],
        state: null,
        key: '',
        pageIndex: 1,
        pageSize: 10,
        total: 0,
        tableData: [],
        options: [{
            value: null,
            label: '全部'
          },{
            value: 0,
            label: '待出库'
          },
          {
            value: 1,
            label: '已装车'
          }, {
            value: 2,
            label: '已出库'
          },{
            value: 3,
            label: '已完结'
          },
          {
            value: 4,
            label: '已取消'
          }
        ],
        param:{},
        // 卖货单参数
        showSellOrder: false,
        manufacturerList: [],
        brotherList: [],
        chooseType: [],
        form: {
          "manufacturerId": null,
          // "brotherId": null,
          // "packId": null,
          // "staffId": null,
          "productId": null,
          "grossWeight": null,
          "weight": null,
          "price": null,
          "sellAmount": null,
          "remarks": "",
          "proves": []
        },
        rules: {
          manufacturerId:[{
            required: true,
            message: '请选择卖货厂商',
            trigger: 'change'
          }],
        },
      }
    },
    mounted() {
      // this.stationlist()
      for(let k in this.$route.query){
        if(this.$route.query[k]){
          if(k == 'pageIndex' || k == 'pageSize' || k == 'packStationId'){
            this[k] = parseInt(this.$route.query[k])
          }else if(k == 'startDate' || k == 'endDate'){
            this[k] = this.$route.query[k]
            this.value1 = [this.$route.query['startDate'],this.$route.query['endDate']]
          }else{
            this[k] = this.$route.query[k]
          }
        }
      }
      this.getList()

      // 卖货厂商
      this.getManufacturerList()
      this.getBrother()
    },
    watch: {
      state(value) {
        this.pageIndex = 1
        this.getList()
      }
    },
    methods: {
      time(e){
        if(e && e.length > 0){
          this.startDate = e[0]
          this.endDate = e[1]
          this.timeType = 4
          this.getList()
        }else{
          this.timeType = 0
          this.startDate = ''
          this.endDate = ''
          this.getList()
        }
      },
      clearstate(v) {
        this.getList();
      },
      goBack() {
        this.$router.go(-1)
      },
      // create() {
      //   this.$router.push({
      //     path: '/order/sell/create'
      //   })
      // },
      getList() {
        this.tableData = []
        this.loading = true
        this.param = {
          "pageIndex": this.pageIndex,
          "pageSize": this.pageSize,
          "key": this.key,
          "state": this.state,
          "startDate": this.startDate,
          "endDate": this.endDate,
          "packStationId":this.packStationId,
          "timeType":this.timeType
        }
        return this.$axios.post('/PackStation/OutOrder/List', this.param).then((res) => {
          this.loading = false
          this.tableData = res.rows;
          this.total = res.total;
        }).catch((err) => {
          this.loading = false
        })
      },
      goView(id) {
        let param = []
        for(let k in this.param){
          if(this.param[k]){
          param.push(`${k}=${this.param[k]}`)
          }
        }
        // this.$router.push(`/order/store/list?${param.join('&')}`)

        return '/order/sell/Views?id=' + id
      },
      pageChange(e) { // 页码切换事件
        this.pageIndex = e;
        this.getList()
        // this.$router.push(`/order/store/list?p=${this.pageIndex}`)
      },
      handleSizeChange(val) {
        this.pageIndex = 1;
        this.pageSize = val;
        this.getList()
      },
      getManufacturerList(key = ''){ //获取后端厂商列表
        this.$axios.post('/PackStation/Manufacturer/Select',{
          "PageIndex": 1,
          "PageSize": 999,
          "Key": key
        }).then((res) => {
          console.log(res)
          this.manufacturerList = res.rows
        })
      },
      getBrother(key = '') { //获取小哥列表
        this.$axios.post('/Select/BrotherList',{
          "PageIndex": 1,
          "PageSize": 999,
          "Key": key
        }).then((res) => {
          console.log(res)
          this.brotherList = res.rows
        })
      },
      loadType(node, resolve) { //加载品类
        const {
          level
        } = node;
        if (level == 0) {
          this.$axios.get('/Waste/Type/List').then((res) => {
            node = res.map(function(c) {
              return {
                id: c.id,
                name: c.name,
                leaf: level >= 1
              }
            });
            resolve(node);
          })
        } else {
          if (level == 1) {
            this.$axios.get(`/Waste/product/List`, {
              params:{
                typeId: node.value
              }
            }).then((res) => {
              node = res.map(function(c) {
                return {
                  id: c.id,
                  name: c.name,
                  leaf: level >= 1
                }
              });
              this.tempSmallTypeList = node
              resolve(node);
            })
          } else {
            resolve();
          }
        }
      },
      SelectType(v) { //选择品类
        console.log(v)
        this.form.productId = v[1]
      },
      // 创建卖货单
      createSellOrder() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            console.log(this.form)
            this.$axios.post('/PackStation/OutOrder/Create', this.form).then((res) => {
              this.$message.success('创建成功');
              this.showSellOrder = false
              this.pageIndex = 1
              this.getList()
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      handleFilesSuccess(res, file) {
          // this.form.pics = []
          if (file.status === "success") {
              this.loading = false
              this.form.proves.push(res.path)
          }
      },
      delPics(index){
        this.form.proves.splice(index,1)
      },
    }
  }
</script>

<style lang="scss" scoped>
  .nav-bar {
    padding: 20px 0 0;
  }

  .send {
    margin-top: 15px;
    margin-right: 10px;
  }

  .dialogForm {
    display: flex;
    flex-wrap: wrap;

    .el-form-item {
      width: 50%;
      float: left;

      &.all {
        width: 100%;
      }

      .el-select {
        width: 100%;
      }
    }
  }

  .user-face {
    display: flex;
    align-items: center;
    position: relative;

    .male,
    .female {
      font-size: 14px;
      position: absolute;
      left: 30px;
      top: 0;
      background-color: #fff;
      height: 16px;
      width: 16px;
      line-height: 16px;
      border-radius: 6px;
    }

    .male {
      color: var(--blue);
    }

    .female {
      color: var(--pink);
    }
  }

  .avatar-uploader{
    display: inline-block;
  }
  .pics-list{
    display: inline-block;
    position: relative;
    .el-icon-error{
      position: absolute;
      right: 0;
      top: -7px;
      color: var(--red);
      z-index: 9;
      font-size: 22px;
      cursor: pointer;
      background: #fff;
      border-radius: 50%;
    }
    .item{
      width:150px;
      height:150px;
      border-radius: 6px;
      margin-right: 10px;
    }
  }
</style>
